<template>
	<view class="all">
		<navbar :backgroung="'#cff0c8'" @updateHeight="updateNavbarHeight" />
		<view class="container" :style="{ marginTop: navbarHeight + 'rpx' }">
			<view class="header">
				<view @click="navigatorTo1" class="user">
					<image class="user-icon" src="../../static/resource/yumi-image/5.jpg" mode=""></image>
					<view class="text">Pollen Dispersal</view>
				</view>

			</view>

			<view class="middle">
				<view class="background" />
				<button class="photo-button" @click="photo">＋</button>
			</view>
		</view>
		<div v-if="isLoading" class="loading-indicator">
			Waiting for backend recognition...
		</div>

		<scroll-view class="scroll-container" scroll-y>
			<!-- Table Header -->
			<view class="table-header">
				<text class="header-item1">Thumbnail</text>
				<text class="header-item2">Predicting Result</text>
				<text class="header-item3">Remarks</text>
			</view>
			<div class="msg" v-if="!imageResults.length">{{ msg }}</div>
			<!-- Table Content -->
			<view class="table-row" v-for="(item, index) in imageResults" :key="item.id">
				<image class="thumbnail" :src="item.thumbnail" mode="scaleToFill" />

				<!-- 使用resultTable组件 -->
				<view class="levels">
					<result-table :result="item.result" :credibility="item.credibility" class="result-table" />
				</view>

				<uni-easyinput type="textarea" class="beizhu" v-model="item.beizhu" @focus="storeOriginalRemark(item)"
					@blur="handleBlur(item)" placeholder="Edit" />

			</view>
		</scroll-view>
	</view>
</template>
<script setup>
import {
	ref,
	onMounted,
} from 'vue';
import resultTable from '../../components/resultTable.vue';
import {
	onLoad,
	onShow
} from "@dcloudio/uni-app"
// 静态导入图片压缩工具
import { compressImagePath } from '../../utils/imageCompress.js';
import { getUserId, getToken } from '../../utils/authUtils.js';
const navbarHeight = ref(0);
const imageResults = ref([]); // 存储缩略图和结果
const userId = ref(null);
const token = ref(null);
const isLoading = ref(false); // 创建一个用于控制加载状态的变量
// 用于存储原始备注  
const originalRemarks = ref({});

// Callback to receive height from navbar
const updateNavbarHeight = (height) => {
	navbarHeight.value = height;
};

const navigatorTo1 = () => {
	uni.navigateTo({
		url: '/pages/user/index',
	});
};


const msg = ref()
const getmsg = () => {
	uni.request({
		url: 'https://maize.ltd/yumi/variable/getPredInfo',
		success: (response) => {
			msg.value = response.data.data
		},
	})
};
onShow(async () => {
	try {
		await getmsg();
		userId.value = await getUserId();
		token.value = await getToken();

	} catch (error) {
		// 获取用户信息失败，继续执行
	}
})

var nickname = ref('');
//获取用户昵称
uni.getStorage({
	key: 'user-data',
	success: (res) => {
		const data1 = res.data;
		nickname.value = data1.name;
	}
})

//拍照并上传
const photo = async () => {
	if (!userId.value || !token.value) {
		try {
			userId.value = await getUserId();
			token.value = await getToken();
		} catch (error) {
			// 忽略获取用户信息失败的错误
		}
		uni.showModal({
			title: 'Tip',
			content: 'login first',
			showCancel: false,
			confirmText: 'OK'
		});
		uni.navigateTo({
			url: '/pages/sign/sign',
		})
		return;
	}

	uni.chooseImage({
		count: 5, // 允许最多选择 5 张图片
		sizeType: ['compressed'], // 仅选择压缩图
		sourceType: ['album', 'camera'], // 从相册或相机选择
		success: (res) => {
			const filePaths = res.tempFilePaths; // 获取图片路径数组
			// 无论单图还是多图，都统一调用上传函数
			uploadMultipleToServer(filePaths);
		},
		fail: (err) => {
			// 选择图片失败，不显示提示
		},
	});
};


// 批量上传图片
const uploadMultipleToServer = (filePaths) => {
	// 无论数量多少，都调用统一的上传函数
	uploadImages(filePaths, userId.value);
};

// 统一上传函数：处理单图和多图上传
const uploadImages = async (filePaths, userId) => {
	isLoading.value = true; // 开始加载  
	try {
		// 确保filePaths是数组
		const paths = Array.isArray(filePaths) ? filePaths : [filePaths];

		// 循环上传每张图片
		for (let i = 0; i < paths.length; i++) {
			try {
				// 直接调用单图上传函数
				await uploadSingleImage(paths[i], userId, false); // 最后一个参数表示不关闭加载动画
			} catch (err) {
				// 单张图片上传失败，继续上传其他图片
			}
		}

		// 所有图片上传完成后显示成功提示
		uni.showToast({
			title: 'Upload success',
			icon: 'success'
		});
	} catch (err) {
		getUserId();
		getToken();
		uni.showModal({
			title: 'Tip',
			content: 'Please try again',
			showCancel: false,
			confirmText: 'OK'
		});
	} finally {
		isLoading.value = false; // 结束加载  
	}
};


// 调用原来的单图上传接口  
const uploadSingleImage = async (filePath, userId, closeLoading = true) => {
	// 只有当不是批量上传的第一张图片时才显示加载动画
	if (closeLoading) {
		isLoading.value = true; // 开始加载  
	}
	try {
		// 确保filePath是有效的字符串
		const actualPath = typeof filePath === 'object' ? filePath.uri || filePath.path || filePath.filePath : filePath;
		if (!actualPath) {
			throw new Error('Invalid file path');
		}

		const compressedPath = await compressImagePath(actualPath, { quality: 70 });
		const uploadRes = await uni.uploadFile({
			url: `https://maize.ltd/yumi/sanfenPredict/${userId}`,
			filePath: compressedPath,
			header: {
				'token': token.value,
			},
			name: 'file',
		});
		// console.log(filePath, "文件路径1");
		// 解析响应  
		if (!uploadRes.data) {
			throw new Error('Upload response is empty');
		}

		const data = JSON.parse(uploadRes.data);
		if (data.code === 200) {
			const newRow = {
				id: data.data.id,
				thumbnail: `data:image/jpeg;base64,${data.data.base64Image}`,
				result: data.data.result,
				credibility: data.data.credibility,
				beizhu: '',
			};
			imageResults.value.unshift(newRow);

			// 只有单张上传时才显示成功提示
			if (closeLoading) {
				uni.showToast({
					title: 'Upload success',
					icon: 'success',
				})
			}
		} else {
			getUserId();
			getToken();
			throw new Error(`Upload failed: ${data.message || 'Unknown error'}`);
		}
	} catch (err) {
		getUserId();
		getToken();
		console.error('上传失败:', err);
		// 只有单张上传时才显示错误提示
		if (closeLoading) {
			uni.showModal({
				title: 'Tip',
				content: 'Network error',
				showCancel: false,
				confirmText: 'OK'
			});
		} else {
			// 批量上传时，将错误抛出给上层处理
			throw err;
		}
	} finally {
		// 只有指定了需要关闭加载动画时才关闭
		if (closeLoading) {
			isLoading.value = false; // 结束加载  
		}
	}
};

// 保存原始备注内容  
const storeOriginalRemark = (item) => {
	originalRemarks.value[item.id] = item.beizhu; // 存储当前项的原始备注内容  
};

// 在失去焦点时处理备注更新  
const handleBlur = (item) => {
	const originalRemark = originalRemarks.value[item.id]; // 获取存储的原始备注  
	if (item.beizhu !== originalRemark) { // 比较当前备注和原始备注  
		updateRemark(item.id, item.beizhu); // 如果不同，则更新备注  
	}
};

// 更新备注并上传到服务器  
const updateRemark = (id, remark) => {
	uni.request({
		url: `https://maize.ltd/yumi/sanfenPredict/remark`, // 替换为你的后端接口  
		method: 'PUT',
		data: {
			id: id,
			remark: remark,
		},
		header: {
			'token': token.value,
		},
		success: (res) => {
			if (res.data.code === 200) {
				uni.showToast({
					title: 'updated'
				})
			}
		},
		fail: (err) => {
			uni.showModal({
				title: 'Tip',
				content: 'Network error',
				showCancel: false,
				confirmText: 'OK'
			});
		}
	});
};
</script>

<style lang="less">
@import '../../styles/common-styles.css';

.all {
	height: 100%;
	overflow: hidden;
	background-color: #f5f5f5;

	.user {
		position: fixed;
		top: 80rpx;
		left: 15rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 10rpx;
		// border: 3rpx solid black;
		border-radius: 20rpx;
		background-color: #cff0c8;
		// box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
		z-index: 9999;


		.user-icon {

			width: 60rpx;
			height: 60rpx;
			border-radius: 50%;
			margin-right: 80rpx;
			border: 2rpx solid #000000;
		}

		.text {
			background-color: #cff0c8;
			font-size: 36rpx;
			font-weight: bold;
			margin-left: 80rpx;
			// left: 20%;
			// transform: translate(-50%, -50%);
		}

	}



	.container {
		background-color: #f5f5f5;
		position: relative;
		width: 100%;
		height: auto;
		display: flex;
		flex-direction: column;



		.header {
			position: relative;
			display: flex;
			align-items: center;
			justify-content: center;
			// padding: 20rpx;
			background-color: #d3d3d3;
			border: 1px solid #ddd;
			// margin: 20rpx 0;
			// margin-bottom: 20rpx;

			.title {
				background-color: #d3d3d3;
				font-size: 36rpx; // 字体大小
				font-weight: bold; // 加粗
				text-align: center;

			}


		}

		.middle {
			position: relative;
			display: flex;
			flex-direction: column; // 纵向布局
			align-items: center; // 居中对齐
			height: 300rpx;


			/* 背景图片样式 */
			.background {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background-image: url('../../static/resource/yumi-image/10.jpg');
				background-size: cover;
				background-position: center;
				z-index: 0;
				/* 使其位于最底层 */
			}

			.photo-button {
				position: absolute;
				/* 定位按钮 */
				top: 50%;
				/* 垂直居中 */
				left: 50%;
				/* 水平居中 */
				transform: translate(-50%, -50%);
				/* 按钮中心对齐父容器 */
				height: 300rpx;
				/* 固定高度 */
				width: 100%;
				/* 固定宽度 */
				font-size: 100rpx;
				/* 调整加号字体大小 */
				font-weight: bold;
				color: #fff;
				background-color: rgba(0, 0, 0, 0.6);
				/* 半透明背景 */
				/* 按钮为圆形 */
				display: flex;
				justify-content: center;
				align-items: center;
				/* 确保文字居中 */
				z-index: 1;
				/* 确保按钮在背景图片上方 */
			}

		}


	}

	.scroll-container {

		background-color: #f5f5f5;
		max-height: 870rpx;
		/* 设置最大高度，确保能够滚动 */
		overflow-y: scroll;
		/* 启用垂直滚动 */
		border: 2rpx solid #ddd;

		.msg {
			margin: 20rpx;
			font-size: 40rpx;
		}

		.table-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			/* 垂直居中对齐 */
			padding: 10rpx 20rpx;
			font-weight: bold;
			background-color: #f5f5f5;
			border-bottom: 1px solid #ddd;
			position: sticky;
			top: 0;
			z-index: 9999;

			.header-item1 {
				background-color: #f5f5f5;
				width: 25%;
				text-align: center;
			}

			.header-item2 {
				background-color: #f5f5f5;
				width: 50%;
				text-align: center;
				padding: 10rpx 0rpx;
			}

			.header-item3 {
				background-color: #f5f5f5;
				flex: 1;
				text-align: center;
			}
		}

		.table-row {
			display: flex;
			align-items: center; // 垂直居中对齐  
			justify-content: space-between; // 在行内均匀分布  
			padding: 10rpx;
			border-bottom: 2rpx solid #cdcdcd;

			.thumbnail {
				width: 23%; // 图片占 20%  
				height: 170rpx;
				border-radius: 10rpx;
				margin-right: 10rpx;
				object-fit: contain;
			}

			.levels {
				width: 50%; // 表格占 50%  
				margin-right: 10rpx;
				// 样式由组件内部提供
			}
		}
	}
}
</style>